import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SettingsPage extends StatefulWidget {
  const SettingsPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _SettingsPageState();
  }
}

class _SettingsPageState extends State<SettingsPage> {
  var _userId;
  var _name;
  final textFieldController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _getUserId();
    _getName();
  }

  Future<void> _getUserId() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _userId = prefs.getString("userId");
    });
  }

  Future<void> _getName() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _name = prefs.getString("name") ?? "";
      textFieldController.text = _name;
    });
  }

  Future<void> saveName() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString("name", textFieldController.text);
    setState(() {
      _name = textFieldController.text;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text('Settings'),
        actions: [
          IconButton(
              onPressed: () {
                saveName();
                const snackBar = SnackBar(content: Text('Settings saved.'));
                ScaffoldMessenger.of(context).showSnackBar(snackBar);
                Navigator.pop(context);
              },
              icon: const Icon(
                Icons.save,
                semanticLabel: 'save',
              ))
        ],
      ),
      body: Center(
          child: Column(
        children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                controller: textFieldController,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Name',
                ),
              ),
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'User Id: $_userId',
                style: TextStyle(color: Colors.black.withOpacity(0.5)),
              ),
            ),
          )
        ],
      )),
    );
  }
}
